package com.mengzhilan.util;

import org.xlp.assertion.AssertUtils;
import org.xlp.javabean.JavaBeanPropertiesDescriptor;
import org.xlp.javabean.MethodException;
import org.xlp.javabean.PropertyDescriptor;
import org.xlp.utils.XLPStringUtil;

/**
 * Description: 反射工具类
 * <br/>date: 2023/12/29 15:16
 *
 * @version 1.0
 * @author: xlp
 */
public class ReflectUtils {
    /**
     * 根据字段名称获取该字段的值
     * @param jpd
     * @param o
     * @param fieldName
     * @return
     * @throws NullPointerException 假如参数为null或空，则抛出该异常
     */
    @SuppressWarnings("all")
    public static Object getFieldValue(JavaBeanPropertiesDescriptor<?> jpd, Object o, String fieldName)
            throws MethodException {
        AssertUtils.isNotNull(jpd, "jpd parameter must not be null!");
        AssertUtils.isNotNull(o, "o parameter must not be null!");
        AssertUtils.isNotNull(fieldName, "fieldName parameter must not be null or empty!");
        PropertyDescriptor pd = jpd.getDescriptor(fieldName);
        AssertUtils.isNotNull(pd, "未找到【" + fieldName + "】该字段对应的读方法");
        return pd.executeReadMethod(o);
    }

    /**
     * 根据字段名称获取该字段的值
     * @param jpd
     * @param o
     * @param fieldName
     * @return 假如执行失败，则返回null
     */
    @SuppressWarnings("all")
    public static Object getFieldValueOrNull(JavaBeanPropertiesDescriptor<?> jpd, Object o, String fieldName) {
        if (jpd == null || o == null || XLPStringUtil.isEmpty(fieldName)) return null;
        PropertyDescriptor pd = jpd.getDescriptor(fieldName);
        try {
            return pd.executeReadMethod(o);
        } catch (Exception e) {
            return null;
        }
    }
}
